<?php

require_once('db_access.inc');
require_once('utils.inc');

function add_note($dbc, $uid, $txt){
	$note_id =  rand_str();
	$query = "insert into note_item (user_id, note_id, note_txt, created_on) values('$uid','$note_id','$txt', now())";
	$dbc->execute_query($query);
	return $note_id;
}

function get_notes($dbc, $uid){
	$res = array();
	$query = "select note_id, note_txt from note_item where user_id = '$uid' order by created_on;";
	$result = $dbc->execute_query($query);
	if($result){
		while($row = mysql_fetch_array($result)){
			$res[] = $row;
		}
	}
	return $res;
}

function add_tags($dbc, $uid, $note_id, $tags){
	$tag = strtok($tags, ",");
	while($tag){
		$t = trim($tag);
		$query = "insert into note_tags(user_id, note_id, tag, created_on) values ('$uid','$note_id','$t',now())";
		$dbc->execute_query($query);
		$tag = strtok(",");
	}
}

function get_tags($dbc, $uid, $note_id){
	$res = array();
	$query = "select tag from note_tags where user_id = '$uid' and note_id = '$note_id'";
	$result = $dbc->execute_query($query);
        if($result){
                while($row = mysql_fetch_array($result)){
                        $res[] = $row['tag'];
                }
        }
        return $res;
}

function str_to_array($tags){
	$tgs = array();
        $tag = strtok($tags,",");
        while($tag){
                $t = trim($tag);
                $tgs[] = $t;
                $tag = strtok(",");
        }
	return $tgs;
}

function get_tag_notes($dbc, $uid, $tags){
	$ctr = 0;
	$query = "";
	foreach ($tags as $tag){
		if($query )
			$query .= ", ";
		$q = " (select note_id,tag from note_tags where user_id = '$uid' and tag = '$tag' ) as t$ctr "; 
		$query .= $q;
		$ctr++;
	}
	if($ctr > 1)
		$query .= "where ";
	$ctr2 = 0;
	$whr = "";
	while($ctr2 < ($ctr-1)){
		$v = $ctr2+1;
		if($whr)
			$whr .= " and ";
		$whr .= " t$ctr2.note_id = t$v.note_id  ";
		$ctr2++;
	}	
	$query .= $whr;

	$nquery = "select note_id, note_txt from note_item where user_id = '$uid' and note_id in (select t0.note_id from $query)";
	$result = $dbc->execute_query($nquery);
        if($result){
                while($row = mysql_fetch_array($result)){
                        $res[] = array($row['note_id'],$row['note_txt']);
                }
        }
        return $res;

}

function get_user_tags($dbc, $uid, $t){
	$res = array();
	$query = "select distinct tag from note_tags where user_id = '$uid' and tag like '$t%' ";
	$result = $dbc->execute_query($query);
	if($result){
		while($row = mysql_fetch_array($result)){
			$res[] = $row['tag'];
		}
	}
	return $res;
}

?>
